﻿using EasyDDD.AdminModule.Domain.AggregateSysAdmin;
using System.Text.Json.Serialization;

namespace EasyDDD.AdminModule.Application.CommandsSysAdmin
{
    [AutoMapperTo(typeof(SysAdmin))]
    public record SysAdminCreateCommand : ICommand<SysAdmin>
    {
        public string NickName { get; set; } = default!;
        public string UserName { get; set; } = default!;
        public string PhoneNumber { get; set; } = default!;
        public string Email { get; set; } = default!;
        [JsonPropertyName("password")]
        public string PasswordHash { get; set; } = default!;
        //public string Sex { get; set; } = default!;
        //public string Dept { get; set; } = default!;
        public string Remark { get; set; } = default!;
    }
    public class SysAdminCreateCommandValidator : AbstractValidator<SysAdminCreateCommand>
    {
        public SysAdminCreateCommandValidator(Repository.SysAdminRepository repository)
        {
            var query = repository.AsQueryable();

            RuleFor(x => x.UserName).NotEmpty().MaximumLength(20)
                .WithMessage("用户名不能为空");
            RuleFor(x => x.PhoneNumber).NotEmpty().MaximumLength(20)
                .WithMessage("手机不能为空");
            RuleFor(x => x.PasswordHash).NotEmpty().MaximumLength(50)
                .WithMessage("密码不能为空");
            //RuleFor(x => x.Password).Matches("/^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$/")
            //    .WithMessage("密码强度不够");

            RuleFor(x => x).Must(input => !query.Any(e => e.UserName == input.UserName))
                .WithMessage("用户名不能重复");
            RuleFor(x => x).Must(input => !query.Any(e => e.PhoneNumber == input.PhoneNumber))
                .WithMessage("手机不能重复");
            RuleFor(x => x).Must(input => !query.Any(e => e.Email == input.Email))
                .WithMessage("邮箱不能重复");
        }
    }
    public class SysAdminCreateCommandHandler(
        IMapper mapper,
        Repository.SysAdminRepository repository,
        ILogger<SysAdminCreateCommandHandler> logger)
        : ICommandHandler<SysAdminCreateCommand, SysAdmin>
    {
        public async Task<SysAdmin> Handle(SysAdminCreateCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysAdminCreateCommandHandler");

            //var entity = mapper.Map<SysAdmin>(request);
            //entity.Add();
            //return repository.AddAsync(entity);

            var entity = mapper.Map<SysAdmin>(request);
            await repository.MarkAsync(entity);
            entity.Add();
            return entity;
        }
    }

}
